package dao

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"seichat/biz"
)

type MessageDao interface {
	RedisMsg(ctx context.Context, key string, start int64, end int64, isRev bool) ([]string, error)
	SendMsgAndSave(ctx context.Context, key string, msg []byte) error
}
type GormMessageDao struct {
	Redis *redis.Client
}

func NewMessageDao(client *redis.Client) MessageDao {
	return &GormMessageDao{
		Redis: client,
	}
}

// RedisMsg 获取缓存里面的聊天记录
func (m *GormMessageDao) RedisMsg(ctx context.Context, key string, start int64, end int64, isRev bool) ([]string, error) {
	var reals []string
	var err error
	if isRev {
		reals, err = m.Redis.ZRange(ctx, key, start, end).Result()
	} else {
		reals, err = m.Redis.ZRevRange(ctx, key, start, end).Result()
	}
	if err != nil {
		return nil, biz.ListNotFound
	}
	return reals, nil
}

func (m *GormMessageDao) SendMsgAndSave(ctx context.Context, key string, msg []byte) error {
	//创建记录
	res, err := m.Redis.ZRevRange(ctx, key, 0, -1).Result()
	if err != nil {
		fmt.Println(err)
	}

	//将聊天记录写入数据库
	score := float64(cap(res)) + 1
	_, e := m.Redis.ZAdd(ctx, key, &redis.Z{Score: score, Member: msg}).Result() //jsonMsg
	if e != nil {
		return e
	}
	return nil
}
